package com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.SelectAgentAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.SnlistAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.MySelectAgentBean;
import com.laiyima.zhongjiang.linghuilv.demo.bean.SnListBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class SelectiveTransferFragment extends Fragment implements View.OnClickListener, ListViewPlus.ListViewPlusListener {
    private String TAG = "SelectiveTransferFragment";
    private int slCode;
    private Button button;
    private LinearLayout linearLayout;
    private LinearLayout mycheckBox;
    private ImageView all;
    private int cb = 1;
    private ListViewPlus mListView;
    private SnListBean mSnListBean;
    private SnlistAdapter mSnlistAdapter;
    private List<SnListBean> SnListBeanListBean = new ArrayList<>();
    private TextView textView;
    private String select_sn = "";
    private int selectCode = 0;
    private EditText input_selsect_sn;
    private String inputSn="";

    private int count, page_count, page_index;

    @Override
    public void onRefresh() {
        SnListBeanListBean.clear();
        intView();
        mSnlistAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {
        if (page_index < page_count) {

            loadData(ListViewPlus.LOAD);
        } else {
            Toast.makeText(getContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:

                    Log.e(TAG, "onRefresh:");
                    onLoadComplete();
                     Toast.makeText(getContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    Log.e(TAG, "onLoadMore:");
                    loadMode(page_index,inputSn);
                    Toast.makeText(getContext().getApplicationContext(), "已加载数据", Toast.LENGTH_SHORT).show();
                    break;
            }

        }

    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }

    private void loadMode(int page_index,String inputSn) {
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/select_transfer");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("sn", inputSn);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("page_index", page_index);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    slCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String sn = value.getString("sn");
                        mSnListBean = new SnListBean(sn);
                        SnListBeanListBean.add(mSnListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (slCode == 200) {

                    mSnlistAdapter = new SnlistAdapter(getContext().getApplicationContext(), SnListBeanListBean);
                    mSnlistAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mSnlistAdapter);

                }

                if (slCode == 500) {
                    Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                onLoadComplete();
            }
        });

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragmen
        View view = inflater.inflate(R.layout.fragment_selective_transfer, container, false);
        button = view.findViewById(R.id.select_button);
        button.setOnClickListener(this);
        linearLayout = view.findViewById(R.id.show_list_sn);

        mListView = (ListViewPlus) view.findViewById(R.id.sn_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);
        setListener();
        mycheckBox = view.findViewById(R.id.SelectivecheckBox);
        mycheckBox.setOnClickListener(this);
        textView = view.findViewById(R.id.sn_count);
        all=view.findViewById(R.id.allselect_image);
        all.setOnClickListener(this);
        input_selsect_sn=view.findViewById(R.id.input_selsect_sn);
        input_selsect_sn.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                inputSn=input_selsect_sn.getText().toString();
                SnListBeanListBean.clear();
                findView(inputSn);

                if(inputSn.length()==0){
                    inputSn="";
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        setLongClick();
        intView();
        return view;
    }

    private void setLongClick(){
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {




                return false;
            }
        });
    }







    private void setListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListViewPlus listView = (ListViewPlus) parent;
                SnListBean mSnListBean = (SnListBean) listView.getItemAtPosition(position);
                String sn = mSnListBean.getSn();
                if (mSnListBean.isChecked()) {
                    select_sn = select_sn.replace(sn, "");
                    selectCode = selectCode - 1;
                    mSnListBean.setChecked(false);
                } else {
                    selectCode = selectCode + 1;
                    select_sn = "," + sn + select_sn;
                    mSnListBean.setChecked(true);
                }
                textView.setText(selectCode+"/"+count);
                mSnlistAdapter.notifyDataSetChanged();
            }
        });

    }
    private void findView(String  inputSn) {
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/select_transfer");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("sn", inputSn);
        params.addBodyParameter("page_size", 10);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    slCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        count = jsonObjec.optInt("count", 0);
                        page_count = jsonObjec.optInt("page_count", 0);
                        page_index = jsonObjec.optInt("page_index", 0);
                        textView.setText("" + count);
                    }
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String sn = value.getString("sn");
                        mSnListBean = new SnListBean(sn);
                        SnListBeanListBean.add(mSnListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (slCode == 200) {
                    mSnlistAdapter = new SnlistAdapter(getContext().getApplicationContext(), SnListBeanListBean);
                    mSnlistAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mSnlistAdapter);
                }

                if (slCode == 500) {
                    Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                onLoadComplete();
            }
        });
    }

    private void intView() {
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/select_transfer");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    slCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        count = jsonObjec.optInt("count", 0);
                        page_count = jsonObjec.optInt("page_count", 0);
                        page_index = jsonObjec.optInt("page_index", 0);
                        textView.setText(0+"/" + count);
                    }
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String sn = value.getString("sn");
                        mSnListBean = new SnListBean(sn);
                        SnListBeanListBean.add(mSnListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (slCode == 200) {
                    mSnlistAdapter = new SnlistAdapter(getContext().getApplicationContext(), SnListBeanListBean);
                    mSnlistAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mSnlistAdapter);
                }

                if (slCode == 500) {
                    Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (SnListBeanListBean.size() == 0) {
                    linearLayout.setVisibility(View.VISIBLE);
                } else {
                    linearLayout.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.select_button:
                dialog_show();
                break;
            case R.id.SelectivecheckBox:
                if (cb == 1) {
                    all.setImageResource(R.drawable.cb_true);
                     cb = 2;
                    for (int i = 0; i < SnListBeanListBean.size(); i++) {
                        select_sn = "," + SnListBeanListBean.get(i).getSn() + select_sn;
                        selectCode = 1;
                        SnListBeanListBean.get(i).setChecked(true);
                    }
                } else {
                    all.setImageResource(R.drawable.cb_fase);
                    cb = 1;
                    for (int i = 0; i < SnListBeanListBean.size(); i++) {
                        selectCode = 0;
                        SnListBeanListBean.get(i).setChecked(false);
                    }
                }
                mSnlistAdapter.notifyDataSetChanged();
                break;
            case R.id.allselect_image:
                if (cb == 1) {
                    all.setImageResource(R.drawable.cb_true);
                    cb = 2;
                    for (int i = 0; i < SnListBeanListBean.size(); i++) {
                        select_sn = "," + SnListBeanListBean.get(i).getSn() + select_sn;
                        selectCode = SnListBeanListBean.size();
                        SnListBeanListBean.get(i).setChecked(true);
                        textView.setText(SnListBeanListBean.size()+"/"+count);
                    }

                } else {
                    textView.setText(0+"/"+count);
                    all.setImageResource(R.drawable.cb_fase);
                    cb = 1;
                    for (int i = 0; i < SnListBeanListBean.size(); i++) {
                        selectCode = 0;
                        SnListBeanListBean.get(i).setChecked(false);
                    }
                }

                mSnlistAdapter.notifyDataSetChanged();
                break;
        }

    }


    private void dialog_show1() {
        SelectiveTransferFragment.CustomPopup1 customPopup = new SelectiveTransferFragment.CustomPopup1(getContext());
        new XPopup.Builder(getContext())
                .asCustom(customPopup)
                .show();
    }
    public  class CustomPopup1 extends CenterPopupView {

        private TextView mytextView,banlance_resout;
        public CustomPopup1(@NonNull Context context) {
            super(context);
        }
        @Override
        protected int getImplLayoutId() {
            return R.layout.banlance_custom_popup;
        }
        @Override
        protected void onCreate() {
            super.onCreate();
            banlance_resout=findViewById(R.id.banlance_resout);
            banlance_resout.setText("划拨成功");
            mytextView=findViewById(R.id.balance_tishi);
            mytextView.setText("");
            findViewById(R.id.banlance_dialog_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
        protected void onShow() {
            super.onShow();
        }
    }




    private void dialog_show() {
        CustomPopup customPopup = new CustomPopup(getContext());
        new XPopup.Builder(getContext())
                .asCustom(customPopup)
                .show();

    }

    public class CustomPopup extends CenterPopupView {
        private MySelectAgentBean mMySelectAgentBean;
        private SelectAgentAdapter mSelectAgentAdapter;
        private ListView listView;
        private List<MySelectAgentBean> MySelectAgentBeanBean = new ArrayList<>();
        private TextView textView;
        private String agentUid = "a";
        private EditText editText;

        public CustomPopup(@NonNull Context context) {
            super(context);
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.custom_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            textView = findViewById(R.id.yingchanglin);
            listView = findViewById(R.id.show_select_name);
            editText = findViewById(R.id.select_agent_list);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ListView listView = (ListView) parent;
                    MySelectAgentBean mTaxbean = (MySelectAgentBean) listView.getItemAtPosition(position);
                    String admin_name = mTaxbean.getAdmin_name();
                    editText.setText(admin_name);
                    agentUid = mTaxbean.getUid().toString();
                    textView.setVisibility(VISIBLE);
                    listView.setVisibility(GONE);
                }
            });
            findViewById(R.id.select_agent_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (selectCode == 0) {
                        Toast.makeText(getContext().getApplicationContext(), "请选要划拨的号", Toast.LENGTH_SHORT).show();
                    } else {
                        if (agentUid.equals("a")) {
                            Toast.makeText(getContext().getApplicationContext(), "请选择划拨的服务商", Toast.LENGTH_SHORT).show();
                        } else {


                            RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/upload");
                            params.addBodyParameter("uid", agentUid);
                            params.addBodyParameter("sn", select_sn);

                            x.http().post(params, new Callback.CommonCallback<String>() {
                                @Override
                                public void onSuccess(String result) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(result);
                                        slCode = jsonObject.optInt("code", 0);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                    if (slCode == 200) {
                                        dismiss();
                                        dialog_show1();
                                        mSnlistAdapter.notifyDataSetChanged();
                                        select_sn = "";
                                        selectCode = 0;
                                        all.setImageResource(R.drawable.cb_fase);
                                        cb = 1;
                                    }
                                    if (slCode == 500) {

                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    Log.e(TAG, "回调失败");
                                }

                                @Override
                                public void onCancelled(CancelledException cex) {
                                }

                                @Override
                                public void onFinished() {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Message msg = handler1.obtainMessage();
                                            msg.what = 20;
                                            handler1.sendMessage(msg);
                                        }
                                    }).start();

                                }
                            });

                        }
                    }
                }
            });
            findViewById(R.id.select_agent_list).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    listView.setVisibility(VISIBLE);
                    textView.setVisibility(GONE);
                    intGetName();
                }
            });

            findViewById(R.id.tv_close).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }

        protected void onShow() {
            super.onShow();
        }

        public void intGetName() {
            if (MySelectAgentBeanBean.size() != 0) {
                MySelectAgentBeanBean.clear();
            }
            SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
            String userID = sharedPreferences.getString("userID", "");
            RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/agent_transfer");
            params.addBodyParameter("uid", userID);

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    try {
                        Log.e(TAG, "系统异常mSelectAgentAdapter" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        slCode = jsonObject.optInt("code", 0);
                        String data = jsonObject.optString("data", null);
                        JSONObject jData = new JSONObject(data);
                        JSONArray list = jData.getJSONArray("list");
                        for (int i = 0; i < list.length(); i++) {
                            JSONObject value = list.getJSONObject(i);
                            String admin_name = value.getString("admin_name");
                            String uid = value.getString("uid");
                            mMySelectAgentBean = new MySelectAgentBean(uid, admin_name);
                            MySelectAgentBeanBean.add(mMySelectAgentBean);
                            mSelectAgentAdapter = new SelectAgentAdapter(getContext().getApplicationContext(), MySelectAgentBeanBean);
                            listView.setAdapter(mSelectAgentAdapter);

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (slCode == 200) {
                    }
                    if (slCode == 500) {
                        Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "系统异常");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.e(TAG, "回调失败");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                }

                @Override
                public void onFinished() {
                }
            });
        }
    }

    Handler handler1 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 20:
                    SnListBeanListBean.clear();
                    intView();
                    Log.e(TAG, "刷新");

            }
        }
    };


}